const puppeteer = require("puppeteer-core");
let path = require("path");
let allData = require("../dlt-ai/res/res.json");
let fs = require("fs");

module.exports = async function pc() {
  const browser = await puppeteer.launch({
    headless: true, //有浏览器界面启动
    slowMo: 10, //放慢浏览器执行速度，方便测试观察
    ignoreHTTPErrors: true,
    defaultViewport: { width: 1400, height: 700 },
    args: [
      //启动 Chrome 的参数，详见上文中的介绍
      // '–no-sandbox',
      // '--start-fullscreen'
    ],
  });
  const page = await browser.newPage();
  await page.goto("https://www.55128.cn/zs/12_96.htm?record=50");

  let head = await page.$("thead .sort_up");
  await head?.click();

  let table = await page.$("#chartData");
  let res = await page.evaluate(function (el) {
    let firstTR = el.querySelectorAll("tr")[0];
    let td = firstTR.querySelectorAll("td");

    let red = [],
      blue = [],
      wzjred = [],
      wzjblue = [],
      time = "";
    td.forEach((item, index) => {
      index == 0 && (time = item.innerText);
      if (
        item.className.includes("chartball_red1") ||
        item.className.includes("chartball_red2")
      ) {
        //红色中奖球
        red.push(item.innerText - 0);
      } else if (item.className.includes("chartball_blue")) {
        //绿色中奖球
        blue.push(item.innerText - 0);
      } else if (item.className.includes("miss-yred") && index < 40) {
        wzjred.push(item.innerText - 0 + 1);
      } else if (item.className.includes("miss-yred-c2") && index > 40) {
        wzjblue.push(item.innerText - 0 + 1);
      }
    });
    console.log("时间", time);
    console.log("红色中奖求", red);
    console.log("蓝色中将球", blue);
    console.log("红色未中奖球排列", wzjred);
    console.log("蓝色未中奖排列", wzjblue);
    return {
      time,
      red,
      blue,
      wzjred,
      wzjblue,
    };
  }, table);

  if (!fs.existsSync(path.join(__dirname, "./img"))) {
    fs.mkdirSync(path.join(__dirname, "./img"));
  }

  await page.screenshot({ path: path.join(__dirname, "./img/cp.png") });
  browser.close();
  // res.wzjred = res.wzjred.map((i) => i - 0 + 1);
  // res.wzjblue = res.wzjblue.map((i) => i - 0 + 1);

  for (let i of res.red) {
    res.wzjred.splice(i - 1, 0, 1);
  }
  for (let i of res.blue) {
    res.wzjblue.splice(i - 1, 0, 1);
  }
  if (!allData[res.time]) {
    allData[res.time] = {
      red: res.red,
      blue: res.blue,
      wzjred: res.wzjred,
      wzjblue: res.wzjblue,
    };
    fs.writeFile(
      path.join(__dirname, "../dlt-ai/res/res.json"),
      JSON.stringify(allData, null, 2),
      { flag: "w" },
      () => {}
    );
  }

  return res;
};
